#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <sys/wait.h>

int main()
{
    // 1. 创建管道
    int pipefd[2] = {0};
    int n = pipe(pipefd);
    if(n < 0)
    {
        perror("pipe");
        return 1;
    }
    printf("pipefd[0]: %d, pipefd[1]:%d\n",  pipefd[0], pipefd[1]);
    // 2. fork创建子进程
    pid_t id = fork();
    if(id == 0)
    {
        // child: w
        close(pipefd[0]);
        char *msg = "hello bit";
        // write(pipefd[1], msg, strlen(msg));
        int cnt = 0;
        char ch = 'a';
        int size = 0;
        char outbuffer[1024];
        while(1)
        {
            write(pipefd[1], &ch, 1);
            size++;
            printf("%d\n", size);
            // snprintf(outbuffer, sizeof(outbuffer)-1, "f->c# %s %d %d\n", msg, cnt--, getpid());
            // write(pipefd[1], outbuffer, strlen(outbuffer));
            //if(cnt % 3 == 0)
            //sleep(1);
        }

        exit(0);
    }
    // 父进程
    close(pipefd[1]);
    char buffer[1024];

    char inbuffer[1024];
    while(1)
    {
        sleep(10);
        ssize_t n = read(pipefd[0], inbuffer, sizeof(inbuffer) -1);
        if(n > 0)
        {
            inbuffer[n] = 0;
            printf("%s\n", inbuffer);
        }
        else if (n == 0)
        {
            printf("read pipe end of file\n");
            break;

        }
        else
        {
            perror("read");
            break;
        }
        close(pipefd[0]);
        break;
    }

    sleep(10);

    int status = 0;
    pid_t rid = waitpid(id, &status, 0);
    //void(rid);
    if(rid > 0)
    {
        printf("child quit code: %d signal: %d\n", (status>>8)&(0xFF), status&(0x7F));
    }

    return 0;
}
